<template>
  <div class="Cart">
    {{name}}购物车
    <hr>
    <ul>
      <li>
        <span></span>
        <span>商品名</span>
        <span>单价</span>
        <span>数量</span>
        <span>价格</span>
      </li>
      <!-- <li v-for="(c,i) in cart" :key="i" :style="{color:c.active?'red':'black'}"> -->
      <li v-for="(c,i) in cart" :key="c.text" :class="{active:c.active}">
        <span>
          <input type="checkbox" v-model="c.active">
        </span>
        <span>{{c.text}}</span>
        <span>{{c.price}}</span>
        <span>
          <button @click="minus(i)">-</button>
          {{c.count}}
          <button @click="add(i)">+</button>
        </span>
        <span>{{c.price * c.count}}</span>
      </li>
    </ul>
    <hr>
    <div>
      <span>{{activeCount}}/{{count}}</span>
      <span>{{total}}</span>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    name: {
      type: String,
      required: true //必传
    }
  }, //获取父组件的数据

  data() {
    return { cart: [] };
  },
  created() {
    this.cart = JSON.parse(window.localStorage.getItem("cart")) || [];
    this.$bus.$on("addCart", good => {
      const ret = this.cart.find(v => v.text == good.text);
      if (ret) {
        ret.count += 1;
      } else {
        this.cart.push({
          ...good,
          active: true,
          count: 1
        });
      }
    });
  },
  watch: {
    //深层监听
    // cart: {
    //   handler() {
    //     this.serLocal();
    //   },
    //   deep: true   //会影响性能，看情况使用
    // },
    cart() {
      this.serLocal();
    }
  },
  computed: {
    count() {
      return this.cart.length;
    },
    activeCount() {
      return this.cart.filter(v => v.active).length;
    },
    total() {
      return this.cart.reduce((sum, v) => {
        if (v.active) {
          return sum + v.price * v.count;
        }
        return sum;
      }, 0);
      // 上下代码结果效果一样

      // let num = 0;
      // this.cart.forEach(v => {
      //   if (v.active) {
      //     num += v.price * v.count;
      //   }
      // });
      // return num;
    }
  },
  methods: {
    serLocal() {
      window.localStorage.setItem("cart", JSON.stringify(this.cart));
    },
    add(i) {
      this.cart[i].count += 1;
    },
    minus(i) {
      const count = this.cart[i].count;
      if (count > 1) {
        this.cart[i].count -= 1;
      } else {
        this.removed(i);
      }
    },
    removed(i) {
      if (window.confirm(`是否删除${this.cart[i].text}？`)) {
        this.cart.splice(i, 1);
      }
    }
  }
};
</script>

<style>
ul li span {
  display: inline-block;
  width: 20%;
  text-align: center;
}
li.active {
  color: #f00;
  font-weight: 600;
}
div > span {
  display: inline-block;
  width: 50%;
  text-align: center;
}
</style>